package com.ybbase.framework.config.shiro.filter;

import com.ybbase.framework.common.constant.ConfigConstant;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AnyRolesAuthorizationFilter extends AuthorizationFilter {

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) {
        request.setAttribute(ConfigConstant.ANY_ROLES_AUTH_FILTER, true);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
        Boolean afterFiltered = (Boolean) (servletRequest.getAttribute(ConfigConstant.ANY_ROLES_AUTH_FILTER));
        if (BooleanUtils.isTrue(afterFiltered)) {
            return true;
        }
        Subject subject = getSubject(servletRequest, servletResponse);
        String[] rolesArray = (String[]) mappedValue;
        //没有角色限制，有权限访问
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }
        for (String role : rolesArray) {
            // 若当前用户是rolesArray中的任何一个，则有权限访问
            if (subject.hasRole(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setCharacterEncoding(ConfigConstant.CHARACTER_ENCODING);
        httpResponse.setContentType(ConfigConstant.CONTENT_TYPE_JSON);
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }

}
